package com.greenant.store.fragment;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AbsListView;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.greenant.store.R;
import com.greenant.store.adapter.MyEarningListAdapter;
import com.greenant.store.adapter.MyEmrecvListAdapter;
import com.greenant.store.bean.EMRecv;
import com.greenant.store.bean.EMRecvList;
import com.greenant.store.bean.IncomeInfo;
import com.greenant.store.bean.Order;
import com.greenant.store.bean.OrderList;
import com.greenant.store.bean.OrderStatusCode;
import com.greenant.store.service.RetrieveDataAsyn;
import com.greenant.store.service.RetrieveDataListener;
import com.greenant.store.utils.Const;
import com.greenant.store.utils.iLog;

import java.util.ArrayList;
import java.util.List;

public class EarningListFragment extends Fragment {
	private static final String TAG = "GoodsListFragment";

	/**
	 * 收入类型
	 */
	public static final int EARNING_TYPE_SALES = 0;
	public static final int EARNING_TYPE_COMMISSION = 1;
	public static final int EARNING_TYPE_EMS = 2;
	public static final int EARNING_TYPE_EMS_SEND = 3;

	private int orderType = EARNING_TYPE_SALES;
	private String userId;
	private final static String TAG_ORDER_TYPE = "orderType";
	private final static String TAG_USER_ID = "userId";

	private final int expectedCount = 30;

	private List<Order> list = new ArrayList<Order>();
	private List<EMRecv> emrecvList = new ArrayList<EMRecv>();
	MyEarningListAdapter myOrderListAdapter;
	MyEmrecvListAdapter myEmrecvListAdapter;
	private int totalItemCounts = 0;
	private boolean isGettingData = false;

	private TextView noOrderListHint;
	private ListView orderlistView;
	private RelativeLayout nodataView;

	// 订单类型
	ArrayList<Integer> orderTypes = new ArrayList<Integer>();

	private TextView earning_salesToday_title, earning_salesToday, earning_salesCurMonth_title, earning_salesCurMonth,
			earning_salesAll_title, earning_salesAll;

	private Context mContext;

	public static EarningListFragment newInstance(int orderType, String userId) {
		EarningListFragment newFragment = new EarningListFragment();
		Bundle bundle = new Bundle();
		bundle.putInt(TAG_ORDER_TYPE, orderType);
		bundle.putString(TAG_USER_ID, userId);
		newFragment.setArguments(bundle);
		return newFragment;
	}

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		Bundle bundle = this.getArguments();
		if (bundle != null) {
			orderType = bundle.getInt(TAG_ORDER_TYPE, EARNING_TYPE_SALES);
			userId = bundle.getString(TAG_USER_ID);
		}
		registerReciver();
		mContext = this.getActivity().getApplicationContext();
	}

	private void registerReciver() {
		IntentFilter downloadManagerFilter = new IntentFilter();
		downloadManagerFilter.addAction(Const.ORDER_STATUS_CHANGED);
		this.getActivity().getBaseContext().registerReceiver(netManagerReceiver, downloadManagerFilter);
	}

	private BroadcastReceiver netManagerReceiver = new BroadcastReceiver() {

		@Override
		public void onReceive(Context context, Intent intent) {
			if (myOrderListAdapter != null) {
				myOrderListAdapter.notifyDataSetChanged();
			}
		}

	};

	public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
		Bundle bundle = this.getArguments();
		if (bundle != null) {
			orderType = bundle.getInt(TAG_ORDER_TYPE, EARNING_TYPE_SALES);
			userId = bundle.getString(TAG_USER_ID);
		}

		if (orderType == EARNING_TYPE_SALES) {
			// 销售

		} else if (orderType == EARNING_TYPE_COMMISSION) {// 代售

		}

		View contentView = inflater.inflate(R.layout.fragment_earning, container, false);
		orderlistView = (ListView) contentView.findViewById(R.id.orderlist);
		initPullToRefreshListView();

		noOrderListHint = (TextView) contentView.findViewById(R.id.noOrderListHint);
		nodataView = (RelativeLayout) contentView.findViewById(R.id.nodataView);

        if (orderType == EARNING_TYPE_SALES || orderType == EARNING_TYPE_COMMISSION) {
            // 销售,代售
            myOrderListAdapter = new MyEarningListAdapter(list, getActivity());
            orderlistView.setAdapter(myOrderListAdapter);
        } else if (orderType == EARNING_TYPE_EMS) {
            // 代收，代发
            myEmrecvListAdapter = new MyEmrecvListAdapter(emrecvList, getActivity());
            orderlistView.setAdapter(myEmrecvListAdapter);
        }
		

		orderlistView.setOnScrollListener(new AbsListView.OnScrollListener() {

			@Override
			public void onScrollStateChanged(AbsListView view, int scrollState) {

			}

			@Override
			public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
				if (totalItemCount < totalItemCounts && (firstVisibleItem + visibleItemCount) == (totalItemCount - 2)) {
				
					loadMoreData();
				}
			}
		});
		initViews(contentView);
		getFirstData();
		return contentView;
	}

	private void loadMoreData(){
		if (!isGettingData) {
			isGettingData = true;
			
			  if (orderType == EARNING_TYPE_SALES || orderType == EARNING_TYPE_COMMISSION) {
		            // 销售,代售
			      RetrieveDataAsyn.getInstance().getMyWebDeposit(userId, orderType, list.size(), expectedCount,
		                    0, new RetrieveDataListener() {

		                @Override
		                public void dataRetrieved(int requestId, Object data) {
		                    if (data != null) {
		                        OrderList orderList = (OrderList) data;
		                        totalItemCounts = orderList.getTotalNum();
		                        list.addAll(orderList.getOrderList());
		                        myOrderListAdapter.notifyDataSetChanged();
		                    }
		                    isGettingData = false;
		                }
		            });  
		        } else if (orderType == EARNING_TYPE_EMS) {
		            // 代收，代发
		            RetrieveDataAsyn.getInstance().getEMRecv(userId, orderType, emrecvList.size(), expectedCount, 0, new RetrieveDataListener() {
		                
		                @Override
		                public void dataRetrieved(int requestId, Object data) {
		                    if (data != null) {
                                EMRecvList orderList = (EMRecvList) data;
                                totalItemCounts = orderList.getTotalNum();
                                emrecvList.addAll(orderList.getEmrecvList());
                                myEmrecvListAdapter.notifyDataSetChanged();
                            }
                            isGettingData = false;}
		            });  
		        }else{
		            isGettingData = false;
		        }

			

		}
	}
	
	public void getFirstData() {
	    iLog.d(TAG,"orderType:"+orderType);
	    if (orderType == EARNING_TYPE_SALES || orderType == EARNING_TYPE_COMMISSION) {
            // 销售,代售
	        RetrieveDataAsyn.getInstance().getMyWebDeposit(userId, orderType, 0, expectedCount, 0,
	                new RetrieveDataListener() {

	                    @Override
	                    public void dataRetrieved(int requestId, Object data) {
	                        list.clear();
	                        refreshWithData();
	                        iLog.d(TAG, "onRefreshComplete:" + data);
	                        if (data != null) {

	                            OrderList orderList = (OrderList) data;
	                            totalItemCounts = orderList.getTotalNum();
	                            list.addAll(orderList.getOrderList());
	                            if (list.size() == 0) {
	                                refreshNoData();
	                            }
	                        } else {
	                            refreshNoData();
	                        }
	                        myOrderListAdapter.notifyDataSetChanged();
	                    }
	                });
        } else if (orderType == EARNING_TYPE_EMS) {
            // 代收，代发
            //TODO 558e0fe4e4b060308e3cb18c userId
            RetrieveDataAsyn.getInstance().getEMRecv(userId, orderType, 0, expectedCount, 0, new RetrieveDataListener() {
                
                @Override
                public void dataRetrieved(int requestId, Object data) {
                    emrecvList.clear();
                    refreshWithData();
                    
                    iLog.d(TAG, "onRefreshComplete:" + data);
                    if (data != null) {

                        EMRecvList orderList = (EMRecvList) data;
                        totalItemCounts = orderList.getTotalNum();
                        emrecvList.addAll(orderList.getEmrecvList());
                        if (emrecvList.size() == 0) {
                            refreshNoData();
                        }
                    } else {
                        refreshNoData();
                    }
                    myEmrecvListAdapter.notifyDataSetChanged();
                    
                }
            });
        }
		
Log.d(TAG, "getIncomeInfo:"+userId);
		// 获取收入信息
		RetrieveDataAsyn.getInstance().getIncomeInfo(userId, 0, new RetrieveDataListener() {

			@Override
			public void dataRetrieved(int requestId, Object data) {
				if (data != null) {
					IncomeInfo incomeInfo = (IncomeInfo) data;

					if (orderType == EARNING_TYPE_SALES || orderType == EARNING_TYPE_COMMISSION) {
						earning_salesToday_title.setText(R.string.earning_salesToday);
						earning_salesCurMonth_title.setText(R.string.earning_salesCurMonth);
						earning_salesAll_title.setText(R.string.earning_salesAll);

						if (orderType == EARNING_TYPE_SALES) {
							earning_salesToday.setText("￥" + incomeInfo.getSalesToday());
							earning_salesCurMonth.setText("￥" + incomeInfo.getSalesCurMonth());
							earning_salesAll.setText("￥" + incomeInfo.getSalesAll());
						} else {
							earning_salesToday.setText("￥" + incomeInfo.getCommissionToday());
							earning_salesCurMonth.setText("￥" + incomeInfo.getCommissionCurMonth());
							earning_salesAll.setText("￥" + incomeInfo.getCommissionAll());
						}

					} else if (orderType == EARNING_TYPE_EMS || orderType == EARNING_TYPE_EMS_SEND) {
						if (orderType == EARNING_TYPE_EMS) {// 代收
							earning_salesToday_title.setText(mContext.getString(R.string.earning_ems_Todaycount,
									incomeInfo.getEMRecvCountToday()));
							earning_salesCurMonth_title.setText(mContext.getString(R.string.earning_ems_Monthcount,
									incomeInfo.getEMRecvCountCurMonth()));
							earning_salesAll_title.setText(
									mContext.getString(R.string.earning_ems_AllCount, incomeInfo.getEMRecvCountAll()));
							earning_salesToday.setText("￥" + incomeInfo.getEMRecvIncomeToday());
							earning_salesCurMonth.setText("￥" + incomeInfo.getEMRecvIncomeCurMonth());
							earning_salesAll.setText("￥" + incomeInfo.getEMRecvIncomeAll());
						} else {// 代发
							earning_salesToday_title.setText(
									mContext.getString(R.string.earning_ems_Todaycount, incomeInfo.getEMSCountToday()));
							earning_salesCurMonth_title.setText(mContext.getString(R.string.earning_ems_Monthcount,
									incomeInfo.getEMSCountCurMonth()));
							earning_salesAll_title.setText(
									mContext.getString(R.string.earning_ems_AllCount, incomeInfo.getEMSCountAll()));
							earning_salesToday.setText("￥" + incomeInfo.getEMSIncomeToday());
							earning_salesCurMonth.setText("￥" + incomeInfo.getEMSIncomeCurMonth());
							earning_salesAll.setText("￥" + incomeInfo.getEMSIncomeAll());
						}

					}
				}

			}
		});
	}

	private void initViews(View contentView) {

		earning_salesToday_title = (TextView) contentView.findViewById(R.id.earning_salesToday_title);
		earning_salesToday = (TextView) contentView.findViewById(R.id.earning_salesToday);

		earning_salesCurMonth_title = (TextView) contentView.findViewById(R.id.earning_salesCurMonth_title);
		earning_salesCurMonth = (TextView) contentView.findViewById(R.id.earning_salesCurMonth);

		earning_salesAll_title = (TextView) contentView.findViewById(R.id.earning_salesAll_title);
		earning_salesAll = (TextView) contentView.findViewById(R.id.earning_salesAll);

		//
		// <string name="earning_salesToday">今日收入：</string>
		// <string name="earning_salesCurMonth">当月收入：</string>
		// <string name="earning_salesAll">累计收入：</string>
		//
		// <string name="earning_ems_Todaycount">今日%1$s件</string>
		// <string name="earning_ems_Monthcount">当月%1$s件</string>
		// <string name="earning_ems_AllCount">合计%1$s件</string>

		if (orderType == EARNING_TYPE_SALES || orderType == EARNING_TYPE_COMMISSION) {
			earning_salesToday_title.setText(R.string.earning_salesToday);
			earning_salesCurMonth_title.setText(R.string.earning_salesCurMonth);
			earning_salesAll_title.setText(R.string.earning_salesAll);

		} else if (orderType == EARNING_TYPE_EMS || orderType == EARNING_TYPE_EMS_SEND) {
			earning_salesToday_title.setText(mContext.getString(R.string.earning_ems_Todaycount, 0));
			earning_salesCurMonth_title.setText(mContext.getString(R.string.earning_ems_Monthcount, 0));
			earning_salesAll_title.setText(mContext.getString(R.string.earning_ems_AllCount, 0));
		}
	}

	public void initPullToRefreshListView() {
		// ILoadingLayout startLabels = orderlistView
		// .getLoadingLayoutProxy(true, false);
		// startLabels.setPullLabel(mContext.getString(R.string.pull_to_refresh));//
		// 刚下拉时，显示的提示
		// startLabels.setRefreshingLabel(mContext.getString(R.string.pull_to_refreshing));//
		// 刷新时
		// startLabels.setReleaseLabel(mContext.getString(R.string.pull_to_refreshbegin));//
		// 下来达到一定距离时，显示的提示

		// ILoadingLayout endLabels = orderlistView.getLoadingLayoutProxy(
		// false, true);
		// endLabels.setPullLabel("上拉刷新...");// 刚下拉时，显示的提示
		// endLabels.setRefreshingLabel("正在载入...");// 刷新时
		// endLabels.setReleaseLabel("放开刷新...");// 下来达到一定距离时，显示的提示

		// // 设置下拉刷新文本
		// pullToRefresh.getLoadingLayoutProxy(false, true)
		// .setPullLabel("上拉刷新...");
		// pullToRefresh.getLoadingLayoutProxy(false, true).setReleaseLabel(
		// "放开刷新...");
		// pullToRefresh.getLoadingLayoutProxy(false, true).setRefreshingLabel(
		// "正在加载...");
		// // 设置上拉刷新文本
		// pullToRefresh.getLoadingLayoutProxy(true, false)
		// .setPullLabel("下拉刷新...");
		// pullToRefresh.getLoadingLayoutProxy(true, false).setReleaseLabel(
		// "放开刷新...");
		// pullToRefresh.getLoadingLayoutProxy(true, false).setRefreshingLabel(
		// "正在加载...");
	}

	public void refreshNoData() {
		noOrderListHint.setVisibility(View.VISIBLE);
		orderlistView.setVisibility(View.INVISIBLE);
		nodataView.setVisibility(View.INVISIBLE);
	}

	public void refreshWithData() {
		noOrderListHint.setVisibility(View.INVISIBLE);
		orderlistView.setVisibility(View.VISIBLE);
		nodataView.setVisibility(View.INVISIBLE);
	}

	@Override
	public void onDestroy() {
		this.getActivity().getBaseContext().unregisterReceiver(netManagerReceiver);
		super.onDestroy();
		Log.d(TAG, "MyStoreFragment-----onDestroy");
	}

}
